package com.imooc.service;

import com.imooc.es.pojo.Items;
import com.imooc.utils.PagedGridResult;
import lombok.AllArgsConstructor;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class EsServiceImpl implements EsService {

    private final ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
        //定义高亮
        String preTag = "<font color='red'>";
        String postTag = "</font>";
        //分页
        Pageable pageable = PageRequest.of(page, pageSize);
        //检索字段
        String fileName = "itemName";
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery(fileName, keywords))
                .withHighlightFields(new HighlightBuilder.Field(fileName)
                        .preTags(preTag)
                        .postTags(postTag))
                .withPageable(pageable)
                .build();

        AggregatedPage<Items> pageItems = elasticsearchTemplate.queryForPage(query, Items.class, new MySearchResult());

        PagedGridResult gridResult = new PagedGridResult();
        gridResult.setRows(pageItems.getContent());
        gridResult.setPage(page + 1);
        gridResult.setTotal(pageItems.getTotalPages());
        gridResult.setRecords(pageItems.getTotalElements());
        return gridResult;
    }


}
